package network.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * @author mubei
 * @date 2021/12/5
 * @description 聊天发送窗口
 */
public class TalkSend {

    DatagramSocket socket = null;
    BufferedReader br = null;

    private String toIp;
    private int toPort;
    private int fromPort;

    public TalkSend(String toIp, int toPort, int fromPort) {
        this.toIp = toIp;
        this.toPort = toPort;
        this.fromPort = fromPort;
        try {
            init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void init() throws Exception {
        socket = new DatagramSocket(this.fromPort);
        br = new BufferedReader(new InputStreamReader(System.in));
    }


    public void run() {
        while (true) {
            String data = null;
            try {
                // 获取键盘输入
                data = br.readLine();
                byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
                DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, new InetSocketAddress(toIp, toPort));
                socket.send(packet);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (data.equals("bye")) {
                    break;
                }
            }
        }
        socket.close();
    }
}
